import CreateRoleTransfer from '../components/CreateRoleTransfer'
import CreateOrgTransfer from '../components/CreateOrgTransfer'
import CreateMsgRoleTransfer from "@/pages/System/RoleAssignment/components/CreateMsgRoleTransfer";
import ImportUser from '../components/ImportUser';
import CreateSocialTransfer from '../components/CreateSocialTransfer';
import CreateSalaryTransfer from '../components/CreateSalaryTransfer';
import React, {useState, useRef, useEffect} from 'react'
import {PageHeaderWrapper} from '@ant-design/pro-layout'
import ProTable, {ProColumns,TableDropdown, ActionType} from '@ant-design/pro-table'
import {connect, history} from 'umi'
import {message, Divider, Button, notification, Popconfirm, Switch ,Menu} from 'antd'
import {getUserList, updateUserRole, updateUserGroup, updateUserMsgRole,
  getBpmUserByCode, deleteUserById, updateUserStatus,updateUserPassword,saveContratctUser,saveSalaryUser} from '../service'

const TableList = () => {
  const actionRef = useRef();
  const [visible, setVisible] = useState(null);
  const [orgTransferVisible, setOrgTransferVisible] = useState(null);
  const [msgRoleTransferVisible, setMsgRoleTransferVisible] = useState(null);
  const [current, setCurrent] = useState(undefined);
  const [importVisible, setImportVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [socialVisible,setSocialVisible] = useState(false);
  const [salaryVisible,setSalaryVisible] = useState(false);

  const showUserRole = (userInfo) => {
    setVisible(true);
    setCurrent(userInfo);
  };

  const showUserGroup = (userInfo) => {
    setOrgTransferVisible(true);
    setCurrent(userInfo);
  };

  const showMsgRole = (userInfo) => {
    setMsgRoleTransferVisible(true);
    setCurrent(userInfo);
  };

  const showSocialRole = (userInfo) => {
    setSocialVisible(true);
    setCurrent(userInfo);
  };

  const showSalaryRole = (userInfo) => {
    setSalaryVisible(true);
    setCurrent(userInfo);
  };

  const deleteUser = (userId) => {
    deleteUserById(userId).then(res => {
      if (res.flag) {
        message.success('删除用户成功！')
      } else {
        message.error(res.error);
      }
      actionRef.current.reload();
    })
  };

  const handleCancel = () => {
    setCurrent(null);
    setVisible(false);
    setSocialVisible(false);
    setSalaryVisible(false);
  };

  const handleImportCancel = () => {
    setCurrent(null);
    setImportVisible(false);
  };

  const handleOrgTransferCancel = () => {
    setCurrent(null);
    setOrgTransferVisible(false);
  };

  const handleMsgRoleTransferCancel = () => {
    setCurrent(null);
    setMsgRoleTransferVisible(false);
  };

  const addUser = () => {
    setImportVisible(true);
  };

  const saveUser = (values) => {
    setLoading(true);
    getBpmUserByCode(values).then(res => {
      if (res.flag) {
        setImportVisible(false);
        actionRef.current.reload();
        message.success("操作成功！");
        notification['success']({
          message: `${res.data.successStr}`,
          duration: null,
          description: <>
            <div>{res.data.existStr}</div>
            <div>{res.data.notFoundStr}</div>
          </>
        });
      } else {
        message.error(res.error);
      }
      setLoading(false)
    });
  };

  const handleSubmit = (values) => {
    let {flag, ...data} = values;
    setCurrent(null);
    if (flag === 'updateOrgGroup') {
      setOrgTransferVisible(false);
      updateUserGroup(data).then(r => {
        if (r.flag) {
          message.success(`用户公司组分配成功。`);
        } else {
          message.error(`用户角色分配失败。${r.error}`);
        }
      })
    } else if (flag === 'updateUserRole') {
      setVisible(false);
      updateUserRole(data).then(r => {
        if (r.flag) {
          message.success(`用户角色分配成功。`);
        } else {
          message.error(`用户角色分配失败。${r.error}`);
        }
      })
    } else if (flag === 'updateUserMsgRole') {
      setMsgRoleTransferVisible(false);
      updateUserMsgRole(data).then(r => {
        if (r.flag) {
          message.success(`用户消息角色分配成功。`);
        } else {
          message.error(`用户消息角色分配失败。${r.error}`);
        }
      })
    }else if(flag === 'social'){
      setSocialVisible(false);
      saveContratctUser(data).then(res => {
        if (res.flag) {
          message.success(`社保组角色分配成功。`);
          actionRef.current.reload();
        } else {
          message.error(`社保组角色分配失败。${res.error}`);
        }
      });
    }else if(flag === 'salary'){
      setSalaryVisible(false);
      saveSalaryUser(data).then(res => {
        if (res.flag) {
          message.success(`薪资组角色分配成功。`);
          actionRef.current.reload();
        } else {
          message.error(`薪资组角色分配失败。${res.error}`);
        }
      });
    }
  };

  const changeUserStatus = (checked,record)=> {
    updateUserStatus(record.userId,checked?1:0).then(res => {
      if (res.flag){
        message.success(`用户启用状态修改成功。`);
      } else {
        message.error(`用户启用状态修改失败。${r.error}`);
      }
      actionRef.current.reload();
    })
  };

  const resetPswd = (id) => {
    updateUserPassword(id).then(res => {
      if (res.flag){
        message.success(`密码重置成功！`);
      } else {
        message.error(`密码重置失败！。${res.error}`);
      }
    })
  };


  const columns = [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`,
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '用户名',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '所属公司',
      dataIndex: 'orgname',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '所属部门',
      dataIndex: 'department',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '岗位',
      dataIndex: 'jobname',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '邮件地址',
      dataIndex: 'email',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '是否启用',
      dataIndex: 'status',
      hideInSearch: true,
      render: (text,record) => {
        return <Switch checkedChildren="是" checked={text !== 0} onChange={(checked) =>changeUserStatus(checked,record)} unCheckedChildren="否" />;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: 'center',
      width:'32%',
      render: (item, record) => (
        <>
          {<a onClick={() => showUserRole(record)}>分配角色</a>}
          {<Divider type="vertical"/>}
          {<a onClick={() => showUserGroup(record)}>公司组</a>}
          {<Divider type="vertical"/>}
          {<a onClick={() => showMsgRole(record)}>消息角色</a>}
          {<Divider type="vertical"/>}
          {<a onClick={() => showSocialRole(record)}>社保组</a>}
          {<Divider type="vertical"/>}
          {<a onClick={() => showSalaryRole(record)}>薪资组</a>}
          {<Divider type="vertical"/>}
          {<Popconfirm title={`是否确认删除?`} onConfirm={() => deleteUser(record.userId)} okText="是" cancelText="否">
            <a>删除</a>
          </Popconfirm>}
          {<Divider type="vertical"/>}
          {<Popconfirm title={`是否重置密码?`} onConfirm={() => resetPswd(record.userId)} okText="是" cancelText="否">
            <a>重置密码</a>
          </Popconfirm>}
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="userId"
        request={(params) => getUserList(params)}
        columns={columns}
        toolBarRender={(action, {selectedRows}) => [
          <Button type="primary" onClick={() => addUser(null)}>导入用户</Button>,
        ]}
      />
      <CreateRoleTransfer
        current={current}
        visible={visible}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      >
      </CreateRoleTransfer>
      <CreateOrgTransfer
        current={current}
        visible={orgTransferVisible}
        onCancel={handleOrgTransferCancel}
        onSubmit={handleSubmit}
      >
      </CreateOrgTransfer>
      <CreateMsgRoleTransfer
        current={current}
        visible={msgRoleTransferVisible}
        onCancel={handleMsgRoleTransferCancel}
        onSubmit={handleSubmit}
      >
      </CreateMsgRoleTransfer>
      <ImportUser
        visible={importVisible}
        loading={loading}
        onCancel={handleImportCancel}
        onSubmit={saveUser}
      >
      </ImportUser>
      <CreateSocialTransfer
        current={current}
        visible={socialVisible}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
      <CreateSalaryTransfer
        current={current}
        visible={salaryVisible}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
    </PageHeaderWrapper>
  )
};

export default connect(({}) => ({}))(TableList)
